package registration;

import java.sql.*;
import javax.servlet.http.*;
import org.apache.struts.action.*;
import org.apache.struts.validator.*;
import org.hibernate.*;
import org.hibernate.cfg.Configuration;
import java.util.*;
import registration.*;
import OnlineExam.db.*;


/**
 *  The user bean to handle all the user operations.
 */


public class User extends HibernateUser
{

	private String passwordConfirm;
	public String getPasswordConfirm()
	{
		return this.passwordConfirm;
	}

	public void setPasswordConfirm(String passwordConfirm)
	{
		this.passwordConfirm = passwordConfirm;
	}
	
	
	/** 
	 * Input validation.
	 */
	
		
	public ActionErrors validate(ActionMapping mapping,HttpServletRequest request) 
	{

		servlet.log ("FirstName : "+ getFirstName());
    	servlet.log("Lastname:" + getLastName());      
    	servlet.log("EmailId : " + getEmailId());      
    	servlet.log("Password:" + getPassword());      
    	servlet.log("Password:" + passwordConfirm);

		ActionErrors errors = new ActionErrors();
    
		if (getFirstName() == null || getFirstName().equals("")) 
		{
      		errors.add("First Name", new ActionMessage("error.firstName"));
    	}

	
		else if (getLastName() == null || getLastName().equals("")) 
		{
      		errors.add("Last Name", new ActionMessage("error.lastName"));
    	}
		
	
  		else if (getEmailId() == null || getEmailId().equals("")) 
		{
      		errors.add("Email Id", new ActionMessage("error.emailId"));
    	}
		
		else if ((getEmailId().indexOf ("@")) == -1)
		{
			errors.add ("Not Valid Id", new ActionMessage ("error.validemailId"));
		}

		else if (getPassword() == null || getPassword().equals("")) 
		{
      		errors.add("Password", new ActionMessage("error.password"));
    	}

		else if (passwordConfirm == null || passwordConfirm.equals (""))
		{
			errors.add ("Confirm Password", new ActionMessage ("error.passwordConfirm"));
		}

		else if (!(passwordConfirm.equals (getPassword())))
		{
			errors.add ("No match", new ActionMessage ("error.nomatch"));
		}
			
		else if (getPassword().length () < 8 || passwordConfirm.length () < 8)
        {
            errors.add ("Too less characters ", new ActionMessage ("error.toosmall"));
        }
		
		else if (isEmailIdPresent (getEmailId()))
		{  
			errors.add ("The User not unique", new ActionMessage ("error.notunique"));
		}
		System.out.println ("error set:" + errors);
    	return errors;	
  	}
	
	
	
	/**
	 *  Checks if the username is already present in the database.
	 */


	private static boolean isEmailIdPresent (String emailIdFromUser)
    {
		Session session = null;
		try
		{
			SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
       		session = sessionFactory.openSession();
		
			Query query = session.createQuery("from User in class registration.HibernateUser where EmailId = :emailId ");  
			query.setString("emailId", emailIdFromUser);

			List list = query.list();
			
			return (list.size() > 0);
		}
		catch (Exception e)
		{
			System.out.println("Exception.." + e);
			return false;
		}
		finally
		{
			try { if (session != null) session.flush(); session.close();}
			catch (Exception e) { System.out.println ("Exception.." + e);}
		}
	}


	/**
	 * returns a list of Tests taken by the given user.
	 */

  	public List retrieveTestsTaken()
  	{

		try
		{
			return DBUtil.select ("Tests", "OnlineExam.Test", "Username", getEmailId());
		}
		catch (DBException e)
		{
			System.out.println ("Exception..." + e);
			System.out.println ("Returnin from the catch block" );
			return null;
		}
  	}
	
	/**
	 *  Returns true iff a user u is the administrator for a given category .  
	 */
	
	public boolean isTheCategoryAdmin(String categoryId) 
	{
		try
		{
			List list = DBUtil.select ("Category", "OnlineExam.Category", "CategoryAdmin", getEmailId(), "CategoryId", categoryId);
			return (list.size() > 0);
		}
		catch (DBException e)
		{
			System.out.println ("dbException.." + e);
			return false;
		}
	}

	/**
	 *  Retrieves all categories being administered by u
	 */
	public List retrieveAdminCategories ()
	{
		
		try 
		{
			return DBUtil.select ("Category", "OnlineExam.Category", "CategoryAdmin", getEmailId());
		}
		catch (DBException e)
		{
			System.out.println ("Exception " + e);
			return null;
		}
	}
}
